package com.quanyue.mechanics.complex.service.impl;

import com.quanyue.auto.util.AssertUtils;
import com.quanyue.mechanics.complex.mapper.ProductMapper;
import com.quanyue.mechanics.complex.service.ProductService;
import com.quanyue.mechanics.complex.type.ProductReq;
import com.quanyue.mechanics.domain.entity.Product;
import com.vhuomai.mybatis.mapper.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product addProduct(Product product) {
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        productMapper.insert(product);
        return product;
    }

    @Override
    public void updateProduct(Product product) {
        Product check = productMapper.findOne(product.getId());
        if (check == null) throw new AssertUtils.ValidateException("error product check");
        product.setCreateTime(check.getCreateTime());
        product.setUpdateTime(LocalDateTime.now());
        productMapper.updateSelective(product);
    }

    @Override
    public void deleteProduct(Integer id) {
        Product check = productMapper.findOne(id);
        if (check == null) throw new AssertUtils.ValidateException("error product check");
        productMapper.deleteOne(id);
    }

    @Override
    public Page <Product> findProductByMenu(ProductReq req) {
        req.setOrderBy("create_time");
        req.setAsc(false);
        if (req.getMenuId() == null) {
            return productMapper.findList(req);
        }
        return productMapper.findListByMenu(req.getMenuId(), req);
    }
}
